package cn.wolfcode.service.impl;

import cn.wolfcode.domain.EmpNotice;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.EmpNoticeMapper;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;

    @Autowired
    private EmpNoticeMapper empNoticeMapper;


    @Override
    public void save(Notice notice) {
        Date now = new Date();
        notice.setCreatTime(now);
        notice.setName(UserContext.getUser().getName());
        notice.setStatus(false);
        noticeMapper.insert(notice);
//        添加的时候,中间表给管理员添加
        EmpNotice empNotice = new EmpNotice();
        empNotice.setNoticId(notice.getId());
        empNotice.setEmpId(UserContext.getUser().getId());
        empNotice.setReaded(false);
        empNoticeMapper.insert(empNotice);
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
        empNoticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Notice>(notices);
    }

    @Override
    public void updatepack(Long id) {
//        改变公告为发布状态,并设置每个员工的状态为可见未读
        Notice notice = noticeMapper.selectByPrimaryKey(id);
        notice.setStatus(true);
        noticeMapper.updatepack(notice);
//        获取当前管理员的id
        Long userid = UserContext.getUser().getId();
//        查询员工
        List<Long> ids = empNoticeMapper.selectAll();
        for (Long  i:ids){
            if (userid!=i){
            EmpNotice empNotice = new EmpNotice();
            empNotice.setReaded(false);
            empNotice.setEmpId(i);
            empNotice.setNoticId(id);
            empNoticeMapper.insert(empNotice);
            }
        }

    }

    @Override
    public List<Notice> selectMinute(Long id, boolean b) {
        return noticeMapper.selectMinute(id,b);
    }
}
